package xin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import xin.entity.TAuthPermission;
import xin.dao.TAuthPermissionMapper;
import xin.service.TAuthPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author young
 * @since 2023年10月09日
 */
@Service
public class TAuthPermissionServiceImpl extends ServiceImpl<TAuthPermissionMapper, TAuthPermission> implements TAuthPermissionService {

    /**
     * 查询所有权限信息
     *
     * @return
     */
    @Override
    public List<TAuthPermission> findAll() {
        return this.baseMapper.findAll();
    }

    @Override
    public TAuthPermission findAllTree() {

        List<TAuthPermission> all = this.findAll();
        all.add(this.baseMapper.selectOne(new QueryWrapper<TAuthPermission>().isNull("parent_id")));
        Map<Long, TAuthPermission> map = all.stream().collect(Collectors.toMap(item -> item.getId(), item -> item));

        map.forEach((key, value) -> {
            if (value.getParentId()!=null){
                TAuthPermission permission = map.get(value.getParentId());
                if (permission.getChildren()==null) permission.setChildren(new ArrayList<>());
                permission.getChildren().add(value);
            }
        });
        return all.get(all.size()-1);
    }
}

